<?php
    session_start();
    include("../include/util.inc.php");
    /****************************
    *Function name: getLogin
    *Description: Returns whether the login was successful or not, 
                    based on the username and password passed in. 
                    If the user name does not exist, it will prompt
                    "This username not exists!"; if the password is 
                    wrong, it will prompt "Wrong password!";
    *Parameters: username; password
    *Return: message
    *******************************/
    function getLogin($username, $pwd){
        $pdo = getPDO();
        $username = $pdo->quote($username);
        $sql = "SELECT * FROM user WHERE username=$username";
        $result = $pdo->query($sql);
        $message = "null";
        if($result->rowCount() == 1){
            $row = $result->fetch();
            if(password_verify($pwd, $row['password'])){
                $_SESSION['uid'] = $row['uid'];
                $message = "success";
            }else{
                $message = "Wrong password! ";
            }
        }else{
            $message = "This username not exists! ";
        }
        return $message;

    }
    /** 
    *Description: Receive the username and password 
    *submitted by js and call the function to determine.
    */
    try {
        $username = $_POST['username'];
        $pwd = $_POST['pwd'];
        $result = getLogin($username, $pwd);
        echo $result;
    } catch (\PDOException $e) {
        echo $e->getMessage();
    }
?>